package com.jn.erp.wechat.common.handler.cp;

import com.jn.erp.web.api.sys.entity.SysOrg;
import com.jn.erp.web.api.sys.service.SysOrgService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * <pre>
 *  企业微信部门机构
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/9/25 9:22
 */
@AllArgsConstructor
@Component
public class CpDepartmentHandler {

    private final WxCpService wxCpService;

    @Autowired
    public CpDepartmentHandler(@Qualifier("wxCpUserService") WxCpService wxCpService){
        this.wxCpService = wxCpService;
    }

    @Autowired
    private SysOrgService sysOrgService;

    //---------------------------------业务-----------------
    public Boolean createDeptById(Long id){
        SysOrg sysOrg = sysOrgService.getById(id);
        Long deptId=create(sysOrg);
        return deptId!=null;
    }
    public Boolean deleteDeptById(Long id){
        return delete(id);
    }

    //---------------------------------接口-----------------
    //新建部门
    public Long create(SysOrg sysOrg) {
        try {
            WxCpDepart depart = new WxCpDepart();
            depart.setName(sysOrg.getName());
            depart.setParentId(1L);
            depart.setOrder(Long.valueOf(sysOrg.getSortNum() + ""));
            depart.setId(sysOrg.getId());
            Long departId = wxCpService.getDepartmentService().create(depart);
            return departId;
        } catch (WxErrorException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    //更新部门
    public Boolean update(SysOrg sysOrg) {
        try {
            WxCpDepart depart = new WxCpDepart();
            depart.setName(sysOrg.getName());
            depart.setParentId(1L);
            if(sysOrg.getSortNum()!=null){
                depart.setOrder(Long.valueOf(sysOrg.getSortNum() + ""));
            }

            depart.setId(sysOrg.getId());
            wxCpService.getDepartmentService().update(depart);
            return true;
        } catch (WxErrorException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    //删除部门
    public Boolean delete(Long id) {
        try {
            wxCpService.getDepartmentService().delete(id);
            return true;
        } catch (WxErrorException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
}
